@file:JvmName("ActivityHelper")

package com.gingko.duominuo.utils

import android.app.Activity
import android.content.Context
import android.text.TextUtils
import com.gingko.duominuo.App
import com.gingko.duominuo.R
import java.util.*
import kotlin.properties.Delegates
import kotlin.system.exitProcess

/**
 * 全局app管理类
 * @author 管理员
 */
val activityStack by lazy { Stack<Activity>() }

/**
 * 添加Activity到堆栈
 */
fun pushActivity(activity: Activity) {
    activityStack.add(activity)
}

/**
 * 获取当前Activity（堆栈中最后一个压入的）
 */
fun currentActivity(): Activity {
    return activityStack.lastElement()
}

/**
 * 结束当前Activity（堆栈中最后一个压入的）
 */
fun popCurrentActivity() {
    val activity = activityStack.lastElement()
    popActivity(activity)
}

/**
 * 结束指定的Activity
 */
fun popActivity(activity: Activity?) {
    activityStack.remove(activity)
    activity?.takeUnless { it.isFinishing }?.finish()
}

/**
 * 结束指定类名的Activity
 */
fun popActivity(cls: Class<*>) {
    activityStack.firstOrNull { it.javaClass == cls }?.let { activity ->
        popActivity(activity)
    }
}

/**
 * 结束某个activity之上的所有activity
 */
fun popAllActivityAboveOne(cls: Class<*>) {
    activityStack.find { it.javaClass == cls } ?: return
    while (true) {
        val activity = activityStack.peek()
        if (activity.javaClass == cls) {
            break
        }
        popActivity(activity)
    }
}


/**
 * 弹出除cls外的所有activity
 *
 * @param cls
 */
fun popAllActivityExceptOne(cls: Class<out Activity?>) {
    while (true) {
        val activity = currentActivity() ?: break
        if (activity.javaClass == cls) {
            break
        }
        popActivity(activity)
    }
}

/**
 * 结束所有Activity
 */
fun popAllActivity() {
    activityStack.forEach { it.finish() }
    activityStack.clear()
}

/**
 * 获取指定的Activity
 * @author kymjs
 */
fun getSpecifiedActivity(cls: Class<*>): Activity? {
    return activityStack.firstOrNull { it.javaClass == cls }
}

/**
 * 退出应用程序
 */
fun AppExit() {
    try {
        popAllActivity()
        // 杀死该应用进程
        android.os.Process.killProcess(android.os.Process.myPid())
        exitProcess(0)
    } catch (e: Exception) {
    }

}

/**
 * 判断某个界面是否在前台
 *
 * @param context
 * @param className 某个界面名称
 */
fun isForeground(context: Context?, className: String): Boolean {
    if (context == null || TextUtils.isEmpty(className)) {
        return false
    }
    val activityManager = context.activityManager
    return activityManager?.let {
        val list = activityManager.getRunningTasks(1)
        if (!list.isNullOrEmpty()) {
            return className == list[0].topActivity?.className
        }
        return false
    } ?: false
}

private var Activity.backPressedTime by Delegates.observable(0L) { pre, old, new ->
    // 2次的时间间隔小于2秒就退出了
    if (new - old < 2000) {
        android.os.Process.killProcess(android.os.Process.myPid())
        exitProcess(0)
    } else {
        App.instance.getString(R.string.please_click_back_again_eixt_app).toast()
    }
}

fun Activity.exitAPP(){
    this.backPressedTime = System.currentTimeMillis()
}